package com.pb.news.web.servlet;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.pb.news.entity.News;
import com.pb.news.service.NewsService;
import com.pb.news.service.impl.NewsServiceImpl;

/**
 * Servlet implementation class AddNewsServlet
 */
@WebServlet("/AddNewsServlet")
public class AddNewsServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public AddNewsServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see Servlet#init(ServletConfig)
	 */
	public void init(ServletConfig config) throws ServletException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see Servlet#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.getWriter().append("Served at: ").append(request.getContextPath());
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		NewsService newsService = new NewsServiceImpl();
		// 接收增加的新闻信息，并调用后台方法，将新闻信息插入数据库
		//request.setCharacterEncoding("utf-8");
		// 解析请求之前，判断是否为文件上传类型
		boolean isMutiPart = ServletFileUpload.isMultipartContent(request);
		// 设置文件上传路径
		String fileUploadPath = request.getSession().getServletContext().getRealPath("upload/");
		News news = new News();
		news.setCreateDate(new Date());
		// 判断目标路径文件是否存在，不存在自动创建
		File saveDir = new File(fileUploadPath);
		if (!saveDir.exists()) {
			saveDir.mkdir();
		}
		if (isMutiPart) { // 处理文件上传
			// 创建文件上传的核心类ServletFileUpload
			FileItemFactory factory = new DiskFileItemFactory();
			ServletFileUpload upload = new ServletFileUpload(factory);
			// 解析请求
			List<FileItem> items;
			try {
				items = upload.parseRequest(request);
				// 获取迭代器
				Iterator<FileItem> iters = items.iterator();
				while (iters.hasNext()) {
					FileItem item = iters.next();
					// 判断fileItem是文本域还是文件域
					if (item.isFormField()) { // 是普通文本表单控件
						String fieldName = item.getFieldName(); // 获取文本域字段name的值
						// 获取文本域value的值
						if (fieldName.equals("categoryId")) {
							news.setCategoryId(Integer.parseInt(item.getString()));
						} else if (fieldName.equals("title")) {
							news.setTitle(item.getString("utf-8"));
						} else if (fieldName.equals("author")) {
							news.setAuthor(item.getString("utf-8"));
						} else if (fieldName.equals("summary")) {
							news.setSummary(item.getString("utf-8"));
						} else if (fieldName.equals("newscontent")) {
							news.setContent(item.getString("utf-8"));
						}
					} else { // 是文件表单控件
						String fileName = item.getName(); // 上传文件名称（全路径）
						if (fileName != null && !fileName.equals("")) {
							File fullFile = new File(fileName);
							File saveFile = new File(fileUploadPath, fullFile.getName());
							item.write(saveFile); // 上传操作
							news.setPicPath(fullFile.getName());
						}
					}
				}
				// 调用后台方法，将新闻信息插入数据库
				boolean flag = newsService.addNews(news);
				if (flag) { // 成功
					// 重定向
					response.sendRedirect("/news5/jsp/admin/newsDetailList.jsp");
				} else { // 不成功
					// 转发
					 request.getRequestDispatcher("/news5/jsp/admin/newsDetailList.jsp").forward(request,
					 response);
				}
			} catch (FileUploadException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}
